package com.ware.jfinal.plugin;


import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import com.jfinal.plugin.IPlugin;
import com.jfinal.plugin.activerecord.IDataSourceProvider;

public class MybatisPlugin  implements IPlugin {
	private static boolean isStarted = false;
	private static IDataSourceProvider dataSourceProvider;
	private static DataSource dataSource;
	
	private static final List<Class> mappers = new ArrayList<Class>();
	/**
	 * 构造函数	
	 */
	public MybatisPlugin(IDataSourceProvider dataSourceProvider){	
		this.dataSourceProvider = dataSourceProvider;
	}
	
	public void addMapper(Class cls){
		mappers.add(cls);
	}
	/**
	 * 停止插件
	 */
	public boolean stop() {
		return true;
	}

	/**
	 * 启动插件
	 */
	public boolean start() {
		if (isStarted)
			return true;
		
		if (dataSourceProvider != null)
			dataSource = dataSourceProvider.getDataSource();
		if (dataSource == null)
			throw new RuntimeException("MybatisPlugin启动失败: 无效的数据源");
		
		TransactionFactory transactionFactory = new JdbcTransactionFactory();
		Environment env =new 	Environment("source",transactionFactory,dataSource);		
		Configuration configuration = new Configuration(env);			
		for(int i=0;i<mappers.size();i++){
			configuration.addMapper(mappers.get(i));
		}
		
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(configuration);
		MY.setSessionFactory(sessionFactory); 			
		isStarted = true;
		
		return true;
	}	
}
